package cc.idoone.spring_boot_hello.ehcache;

import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @auther hemj
 * @since 2017/9/26
 */
@Service
@CacheConfig(cacheNames = "users", cacheManager = "ehCacheCacheManager")
public class EhcacheService {

	@Cacheable
	public Map getFromCache() {
		Map data = new HashMap<>();
		data.put("id", "ehcache");
		data.put("name", "hemj");
		data.put("timestamp", System.currentTimeMillis());
		System.out.println("从方法中读取数据...");
		return data;
	}

	@CacheEvict
	public void deleteFromCache() {
		System.out.println("删除缓存");
	}

	@Cacheable(key = "'keyconcat_' + #p0", unless = "#result == null")
	public Map getFromCache(String key) {
		if ("nocache".equals(key)) {
			System.out.println("从方法中读取数据 nocahce...");
			return null;
		}
		Map data = new HashMap<>();
		data.put("id", key);
		data.put("name", "hemj2017");
		data.put("timestamp", System.currentTimeMillis());
		System.out.println("从方法中读取数据 key...");
		return data;
	}

	@CacheEvict(key = "'keyconcat_' + #p0")
	public void deleteFromCache(String key) {
		System.out.println("删除缓存 key");
	}

	@Cacheable(key = "'keyconcat_' + #map['mapkey']", unless = "#result == null")
	public Map getMapKeyCache(Map map) {
		if ("nocache".equals(map.get("mapkey"))) {
			System.out.println("从方法中读取数据 nocahce...");
			return null;
		}
		Map data = new HashMap<>();
		data.put("id", map.get("mapkey"));
		data.put("name", "hemj2017");
		data.put("timestamp", System.currentTimeMillis());
		System.out.println("从方法中读取数据 key...");
		return data;
	}

	@CacheEvict(key = "'keyconcat_' + #map['mapkey']")
	public void deleteMapKeyCache(Map map) {
		System.out.println("删除缓存 key");
	}
}
